class Solution
{
public:
    vector<int> asteroidCollision(vector<int> &asteroids)
    {
        stack<int> s;
        for (int asteroid : asteroids)
        {
            if (asteroid < 0)
            {
                bool equal = false;
                while (!s.empty())
                {
                    if (s.top() < 0)
                    {
                        s.push(asteroid);
                        break;
                    }
                    else if (s.top() < -asteroid)
                    {
                        s.pop();
                    }
                    else if (s.top() == -asteroid)
                    {
                        s.pop();
                        equal = true;
                        break;
                    }
                    else
                    {
                        break;
                    }
                }
                if (!equal && s.empty())
                {
                    s.push(asteroid);
                }
            }
            else
            {
                s.push(asteroid);
            }
        }
        vector<int> result(s.size());
        for (auto it = result.rbegin(); it != result.rend(); ++it)
        {
            *it = s.top();
            s.pop();
        }
        return result;
    }
};